Leetcode144——Binary Tree Preorder Traversal

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 问题描述

Given a binary tree, return the preorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

1
2
3
4
5
1
\
2
/
3

return [1,2,3].

2. 求解

这个题就是一个树的先序遍历问题,最简单的方案就是递归的遍历子树,要注意递归退出的条件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root == null) {
return list;
}
list.add(root.val);
List<Integer> left = preorderTraversal(root.left);
List<Integer> right = preorderTraversal(root.right);
list.addAll(left);
list.addAll(right);
return list;
}
}
如果有收获,可以请我喝杯咖啡!